import axios from 'axios'
import {Message, Loading} from 'element-ui';
import router from '../router/router'

let loading;        //定义loading变量

function startLoading() {    //使用Element loading-start 方法
    loading = Loading.service({
        lock: true,
        text: '加载中...',
        background: 'rgba(0, 0, 0, 0.7)'
    })
}

function endLoading() {    //使用Element loading-close 方法
    loading.close()
}

// 请求拦截  设置统一header
axios.interceptors.request.use(config => {
    // 加载
    startLoading();
    if (localStorage.token)
        config.headers.token = localStorage.token;
    return config
}, error => {
    return Promise.reject(error)
});

// 响应拦截  401 token过期处理
axios.interceptors.response.use(response => {
    endLoading();
    //拦截错误信息
    if (response.data.code !== 0) {
        Message({
            message: response.data.msg,
            center: true,
            type: 'error'
        });
    }
    return response
}, error => {
    // 错误提醒
    endLoading();

    const {status} = error.response;   //响应头status
    if (status === 401) {
        Message.error('token值无效，请重新登录');
        // 清除token
        localStorage.removeItem('token');

        // 页面跳转
        router.push('/login')
    } else {
        Message({
            message: error.response.data.message,
            center: true,
            type: 'error'
        });
    }
    return Promise.reject(error)
});

export default axios
